package logic

import (
	"context"
	"fmt"
	"good_srv/cache"
	"good_srv/models"

	"good_srv/good"
	"good_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CarAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCarAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CarAddLogic {
	return &CarAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 购物车添加
func (l *CarAddLogic) CarAdd(in *good.CarAddRequest) (*good.CarAddResponse, error) {
	// todo: add your logic here and delete this line
	//用户·是否存在
	var err error
	var user models.User
	if user.UserById(); err != nil {
		logx.Error("用户不存在")
		return nil, fmt.Errorf("用户不存在")
	}
	//商品是否存在
	var goods models.Goods
	goods.ID = uint(in.GoodId)
	if goods.GoodAdd(); err != nil {
		logx.Error("商品不存在")
		return nil, fmt.Errorf("商品不存在")
	}
	if goods.Stock > in.Num {
		logx.Error("库存不存在")
		return nil, fmt.Errorf("库存不存在")
	}
	//购物车存在 存在就增加 不存在就创建
	if cache.CarExist(int(in.UserId), int(in.GoodId)) {
		cache.CarUpdate(int(in.UserId), int(in.GoodId), int(in.Num))
	} else {
		goodMap := map[string]interface{}{
			"userId": in.UserId,
			"num":    in.Num,
			"goodId": in.GoodId,
			"Title":  goods.Title,
			"Stock":  goods.Stock,
			"Price":  goods.Price,
		}
		cache.CarAdd(int(in.UserId), int(in.GoodId), goodMap)
	}
	return &good.CarAddResponse{}, nil
}
